/**
 * 
 */
package com.starhub.sample.webapp.controllers.personal.mobile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * @author Hoan.NguyenTrong Jan 8, 2015
 *
 */
@Controller
@RequestMapping(value = "/resources")
public class ResourceController {

    @Autowired
    private ServletContext context;
    
    /**
     * get image resource files
     * 
     * @param type
     * @param attachLocation
     * @param thumbnail
     * @return
     * @throws IOException 
     */
    @RequestMapping(value = "/images/banners/{fileName:.+}", method = RequestMethod.GET)
    public ResponseEntity<byte[]> getLogoImgFile(@PathVariable("fileName") String fileName) throws IOException {

	    final HttpHeaders headers = new HttpHeaders();
	    headers.setContentType(MediaType.IMAGE_JPEG);

	    String rootPath = System.getProperty("catalina.home");
	    File dir = new File(rootPath + File.separator + "tmpFiles");
	    if (dir.exists()){
		dir.mkdirs();
		// Create the file on server
		InputStream in = new FileInputStream(dir.getAbsolutePath() + File.separator + fileName);
		byte[] body = IOUtils.toByteArray(in);
		in.close();
		return new ResponseEntity<byte[]>(body, headers, HttpStatus.CREATED);
	    }
	    
	    return null;
    }
}
